#include "progressbar.h"
#include "ui_progressbar.h"

#include <QBrush>
#include <QPainter>
#include <QPixmap>
#include <QTimer>

ProgressBar::ProgressBar(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ProgressBar)
{
    ui->setupUi(this);

    auto timer = new QTimer(this);
    connect(timer,&QTimer::timeout,[this](){
        repaint();

//        percentage+=0.001;

//        if(percentage>1){
//            percentage=1;
//        }
    });
    timer->start(10);
}

ProgressBar::~ProgressBar()
{
    delete ui;
}

double ProgressBar::getPercentage() const
{
    return percentage;
}

void ProgressBar::setPercentage(double newPercentage)
{
    if(newPercentage > 1){
        newPercentage = 1.0;
    }

    percentage = newPercentage;
}



void ProgressBar::paintEvent(QPaintEvent *event)
{
    static QPixmap progress(":/qrc/original/img_Progress.png");
    static QPixmap progress100(":/qrc/original/img_Progress_100.png");
    if(percentage > curPercentage){
        curPercentage += 0.1*(percentage-curPercentage);
    }

    QPainter painter(this);
    painter.setPen(Qt::NoPen);
    painter.setBrush(progress);
    painter.save();
    painter.scale((float)this->width()/progress.width(),(float)this->height()/progress.height());
    painter.translate(-progress.width()*(1-curPercentage),0);
    painter.drawRect(progress.width()*(1-curPercentage),0,progress.width()*curPercentage,progress.height());
    painter.restore();

    if(qAbs(curPercentage-1)<0.000001){
        painter.save();
        painter.setBrush(progress100);
        painter.scale((float)this->width()/progress100.width(),(float)this->height()/progress100.height());
        painter.drawRect(0,0,progress100.width(),progress100.height());
        painter.restore();

    }

    painter.setBrush(Qt::NoBrush);
    QPen p(QColor(255,255,255,255));
    p.setWidth(2);
    painter.setPen(p);
    painter.drawRect(1,1,this->width()-1,this->height()-1);
}
